#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 
#include <wait.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>

sem_t Semaphore;


int PutInt_Exosite(char *pCIK, char *pDataAlias, int Data)
{
	int RetVal=0;
	char Command[200];
	//char Result[100];
	char pData[11];
	FILE *fp = NULL;
	
	sprintf(pData, "%d", Data);
	sprintf(Command, "curl -s http://m2.exosite.com/onep:v1/stack/alias \
					-H 'X-Exosite-CIK: %s' \
					-H 'Accept: application/x-www-form-urlencoded; charset=utf-8' \
					-d '%s=%s'", pCIK, pDataAlias, pData);
	//printf("%s\n", Command);				
	fp=popen(Command, "r");
	if(fp){
		fgetc(fp);
		if(feof(fp)){
			//printf("Ok\n");
			RetVal=0;
		}
		else{
			//printf("Fail\n");
			RetVal=-2;
		}
	}	
	else{
		//printf("error [%d:%s]\n", errno, strerror(errno));
		RetVal=-1;
	}	
	pclose(fp);
	return RetVal;
}

int GetInt_Exosite(char *pCIK, char *pDataAlias, int *pData)
{
	int RetVal=0;
	char Command[200];
	char Result[100];
	FILE *fp = NULL;
	char *pChar;
	
	sprintf(Command, "curl -s http://m2.exosite.com/onep:v1/stack/alias?%s \
					-H 'X-Exosite-CIK: %s' \
					-H 'Accept: application/x-www-form-urlencoded; charset=utf-8'", pDataAlias, pCIK);
	fp=popen(Command, "r");
	if(fp){
		fgets(Result, sizeof(Result), fp);
		pChar=strstr(Result, pDataAlias);
		if(pChar != NULL){
			pChar=pChar+strlen(pDataAlias)+1; // '+1' is '='
			*pData=atoi(pChar);
			RetVal=0;
		}
		else{
			//printf("Error\n");
			RetVal=-2;
		}
	}	
	else{
		//printf("error [%d:%s]\n", errno, strerror(errno));
		RetVal=-1;
	}
	pclose(fp);
	return RetVal;
}

void *Thread1(void *data)
{
	volatile int PutData=0;
	while(1){
		printf("P");fflush(stdout);

		if(PutInt_Exosite("bb26ddb330be61752bce11cfb33f4ce204817a3d", "windspeed", PutData)){
			printf("Error: Put\n");
		}
		else{
			//Nothing
		}
		
		printf("%d--", PutData);fflush(stdout);
		sem_post(&Semaphore);
		sleep(5);
		PutData++;
	}
}

void *Thread2(void *data)
{
	int GetData;
	while(1){
		sem_wait(&Semaphore);
		printf("G");fflush(stdout);

		if(GetInt_Exosite("bb26ddb330be61752bce11cfb33f4ce204817a3d","windspeed", &GetData)){
			printf("Error: Get\n");
		}
		else{
			printf("%d\n", GetData);
		}

	}
}

int main( int argc, const char* argv[] )
{
    pthread_t objThread[2];

	sem_init(&Semaphore, 0, 0);
	
    pthread_create(&objThread[0], NULL, Thread1, NULL);
    pthread_create(&objThread[1], NULL, Thread2, NULL);	

    pthread_detach(objThread[0]);
	pthread_detach(objThread[1]);
    pause();

	return -1;	
}

/*
	char CmdLine[100];
	int Len;
	Len=sprintf(CmdLine, "cp test.txt text.%s", "tst");
	printf("%s, %d\n", CmdLine, Len);
	system(CmdLine);
*/


